package com.yuan.util.number;

/**
 * 数字工具类
 * @author YouYuan
 * @link https://gitee.com/you-yuan
 * @version 1.0
 * @Email xiyousuiyuan@163.com
 * @Date 2018/2/2 16:04
 */
public class NumUtil {
    public static final int DEFAULT_COVER_INT_VAL = -1;
    public static final long DEFAULT_COVER_LONG_VAL = -1;
    public static final double DEFAULT_COVER_DOUBLE_VAL = -1.0D;

    public static int toInt(Object o) {
        return toInt(o, DEFAULT_COVER_INT_VAL);
    }

    /**
     * 对象转换成int，若转换失败返回给定的默认值
     * @param o 要转int的对象
     * @param defaultVal 默认值
     * @return
     */
    public static int toInt(Object o, int defaultVal) {
        if (o == null) {
            return defaultVal;
        }
        try {
            return Integer.parseInt(o.toString().trim());
        } catch (Exception e) {
            return defaultVal;
        }
    }

    public static long toLong(Object o) {
        return toLong(o, DEFAULT_COVER_LONG_VAL);
    }

    public static long toLong(Object o, Long defaultVal) {
        if (o == null) {
            return defaultVal;
        }
        try {
            return Long.parseLong(o.toString().trim());
        } catch (Exception e) {
            return defaultVal;
        }
    }

    public static double toDouble(Object o) {
        return toDouble(o, DEFAULT_COVER_DOUBLE_VAL);
    }

    public static double toDouble(Object o, Double defaultVal) {
        if (o == null) {
            return defaultVal;
        }
        try {
            return Double.parseDouble(o.toString().trim());
        } catch (Exception e) {
            return defaultVal;
        }
    }
}
